package cn.edu.ecjtu.android_tutorials;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.MenuBuilder;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;

import android.animation.FloatEvaluator;
import android.animation.ObjectAnimator;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.BounceInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ViewPager page;
    PageAdapter pageAdapter;

    RecyclerView listView;
    ListAdapter listAdapter;
    static List<User> userList;

    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        page = findViewById(R.id.page);

        List<View> viewList = new ArrayList<>();

        View view_r = getLayoutInflater().inflate(R.layout.page_r, null, false);
        View view_g = getLayoutInflater().inflate(R.layout.page_g, null, false);
        View view_b = getLayoutInflater().inflate(R.layout.page_b, null, false);
        viewList.add(view_r);
        viewList.add(view_g);
        viewList.add(view_b);
        pageAdapter = new PageAdapter(viewList);
        page.setAdapter(pageAdapter);


        listView = findViewById(R.id.listview);
        userList = new ArrayList<>();
        userList.add(new User("Tom","13707178987"));
        userList.add(new User("Tom1","18873785502"));
        listAdapter = new ListAdapter(userList);
        Button button1 = (Button)findViewById(R.id.btn_add);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, SecondPage.class);
                intent.putExtra("pos","-1");
                startActivityForResult(intent,1);
            }
        });
        listAdapter.listener = new ListAdapter.ListListener() {
            @Override
            public void onDelUser(final int pos, String name,String phone) {
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage("确定要删除该号码么")
                        .setTitle("删除")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                userList.remove(pos);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        listAdapter.notifyDataSetChanged();
                                    }
                                });
                                dialogInterface.dismiss();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).create().show();}

            @Override
            public void onSelectUser(final int pos, String name,String phone) {
                //toast 输出提示
//                Toast toast = Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT);
//                toast.show();
//                Toast toast = new Toast(MainActivity.this);
//                toast.setView(getLayoutInflater().from(MainActivity.this).inflate(R.layout.toast_image, null, true));
//                toast.show();
//                 对话框提示修改内容页面
//                UserEditDialog dialog = new UserEditDialog(MainActivity.this);
//                dialog.callback = new UserEditDialog.Callback() {
//                    @Override
//                    public void onEditName(String name,String phone) {
//                        userList.get(pos).name = name;
//                        userList.get(pos).phone = phone;
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                listAdapter.notifyDataSetChanged();
//                            }
//                        });
//                    }
//                };
//                dialog.show();
//                System.out.println(name+"号码"+phone);
                Intent intent = new Intent();
                intent.putExtra("name",name);
                intent.putExtra("phone",phone);
                intent.putExtra("pos",pos+"");
                intent.setClass(MainActivity.this, Editpage.class);
                startActivityForResult(intent,1);

            }
        };

        listView.setAdapter(listAdapter);
        RecyclerView.LayoutManager layoutMgr = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
        listView.setLayoutManager(layoutMgr);
        listView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        listAdapter.notifyDataSetChanged();

        final Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toolbar.setVisibility(View.GONE);
            }
        });
//        toolbar.setLogo(R.mipmap.ic_launcher);
        toolbar.setNavigationIcon(R.mipmap.ic_launcher);

        final SwipeRefreshLayout refreshLayout = findViewById(R.id.refresh);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.i("main", "layout");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                }, 2000);
            }
        });

        img = view_r.findViewById(R.id.img);

        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ObjectAnimator objAnime = ObjectAnimator.ofFloat(img, "scaleX", img.getScaleX(), img.getScaleX()+0.1f);
                objAnime.setDuration(800);


                ValueAnimator valAnime = ValueAnimator.ofObject(new FloatEvaluator() {
                    @Override
                    public Float evaluate(float fraction, Number startValue, Number endValue) {
                        return startValue.floatValue() + (endValue.floatValue()-startValue.floatValue()) * fraction;
                    }
                }, 0.5, 1.5);
                valAnime.setDuration(400);
                valAnime.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator valueAnimator) {
                        img.setScaleX((float) valueAnimator.getAnimatedValue());
                    }
                });

//                valAnime.start();


                Animation alphasAnime = new AlphaAnimation(0, 1);
                Animation translateAnime = new TranslateAnimation(0, img.getWidth(), 0, 0);
                final Animation rotateAnime = new RotateAnimation(0, 720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                rotateAnime.setDuration(800);
                rotateAnime.setRepeatCount(1);
                rotateAnime.setRepeatMode(Animation.REVERSE);

                Animation anime = new ScaleAnimation(1.0f, 1.2f, 1.0f, 1.2f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                anime.setDuration(1000);
                anime.setRepeatCount(1);
                anime.setInterpolator(new BounceInterpolator());
                anime.setRepeatMode(Animation.REVERSE);
                anime.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        img.setClickable(false);
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        img.setClickable(true);
//                        img.startAnimation(rotateAnime);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });

                AnimationSet animeSet = new AnimationSet(true);
                animeSet.setDuration(2000);
//                animeSet.setFillAfter(true);
                animeSet.addAnimation(anime);
                animeSet.addAnimation(rotateAnime);
//                img.startAnimation(animeSet);
//                objAnime.start();
                img.startAnimation(anime);

//                objAnime.start();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final float startScale = 1.0f;
                        long duration = 2000;
                        long sps = 20;
                        long t = 0;
                        int idx = 0;

                        while (t < duration) {
                            idx ++;
                            final int finalIdx = idx;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    img.setScaleX(startScale+0.02f* finalIdx);
                                    img.invalidate();
                                }
                            });
                            try {
                                Thread.sleep(sps);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            t += sps;
                        }
                    }
                });//.start();

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
                if(resultCode==RESULT_OK){
//                    String returnData = data.getStringExtra("data_return");
//                    Log.d("FirstActivity","returnData");
                    String pos=data.getStringExtra("pos");
//                    System.out.println("pos"+pos);
                    Log.d("pos",pos);
                    if (Integer.parseInt(pos)==-1){
                        Log.d("pos","1");
                        userList.add(new User(data.getStringExtra("name"),data.getStringExtra("phone")));
                    }
                    else {
                        Log.d("pos",pos);
                        Log.d("name",data.getStringExtra("name"));
                        Log.d("phone",data.getStringExtra("phone"));

                        userList.get(Integer.parseInt(pos)).name =data.getStringExtra("name");
                        userList.get(Integer.parseInt(pos)).phone = data.getStringExtra("phone");

                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listAdapter.notifyDataSetChanged();
                        }
                    });
                }
                break;

        }
    }

}